package com.youlu.campus.admin.wechat;

import com.youlu.campus.admin.utils.AuthUtils;
import com.youlu.campus.common.base.RestResult;
import com.youlu.campus.common.base.RestResultBuilder;
import com.youlu.campus.entity.VO.req.WechatConfigInfoQueryVO;
import com.youlu.campus.entity.WechatConfigInfo;
import com.youlu.campus.service.wechat.WechatConfigInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;

@RestController
public class WechatAuthorizeConfigController {
    @Autowired
    private WechatConfigInfoService wechatConfigInfoService;

    @PostMapping("/wechat/authorize-config/list")
    public RestResult list(@RequestBody @Valid WechatConfigInfoQueryVO req) {
        String comId = AuthUtils.getComId();
        Page<WechatConfigInfo> datas = wechatConfigInfoService.list(req);
        if (datas == null) {
            PageRequest pageRequest = PageRequest.of(req.getPage() - 1, req.getPageSize());
            datas = PageableExecutionUtils.getPage(new ArrayList<>(), pageRequest, () -> 0L);
        }
        return RestResultBuilder.builder().success().data(datas).build();
    }

    @PostMapping("/wechat/authorize-config/create")
    public RestResult create(@RequestBody @Valid WechatConfigInfo req) {
        String comId = AuthUtils.getComId();
        boolean re = wechatConfigInfoService.create(req);
        if (re) {
            return RestResultBuilder.builder().success().data(re).build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    @PostMapping("/wechat/authorize-config/update")
    public RestResult update(@RequestBody @Valid WechatConfigInfo req) {
        String comId = AuthUtils.getComId();
        boolean re = wechatConfigInfoService.update(req);
        if (re) {
            return RestResultBuilder.builder().success().data(re).build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    @GetMapping("/wechat/authorize-config/find-one")
    public RestResult findOne(@RequestParam("id") String id) {
        String comId = AuthUtils.getComId();
        WechatConfigInfo re = wechatConfigInfoService.findOne(id);
        return RestResultBuilder.builder().success().data(re).build();
    }

    @GetMapping("/wechat/authorize-config/delete")
    public RestResult delete(@RequestParam("id") String id) {
        String comId = AuthUtils.getComId();
        boolean re = wechatConfigInfoService.delete(id);
        if (re) {
            return RestResultBuilder.builder().success().data(re).build();
        }
        return RestResultBuilder.builder().failure().build();
    }
}